package com.liuxu.supernews;

import android.accessibilityservice.AccessibilityService;
import android.accessibilityservice.AccessibilityServiceInfo;
import android.annotation.TargetApi;
import android.content.ClipData;
import android.content.ClipboardManager;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.KeyEvent;
import android.view.accessibility.AccessibilityEvent;
import android.view.accessibility.AccessibilityManager;
import android.view.accessibility.AccessibilityNodeInfo;
import android.widget.Toast;

import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
import java.util.List;

public class AccessService extends AccessibilityService {
    private AccessibilityManager mAccessibilityManager;
    public Thread MyThread;
    public int search_count=5;
    public void onCreate() {
        super.onCreate();
        Log.e("Service", "onCreate");

    }

    public void onDestroy() {
        super.onDestroy();
        Log.e("Service", "onDestroy");

    }
    @Override
    public boolean onKeyEvent(KeyEvent event) {
        Log.i("按键", "onKeyEvent");
        if(MyApplication.permission) {
            int key = event.getKeyCode();
            switch (key) {
                case KeyEvent.KEYCODE_VOLUME_DOWN:
                    Log.i("按键", "KEYCODE_VOLUME_DOWN");
                    showtoast("停止运行");
                    MyApplication.permission=false;
                    super.onDestroy();
                    return true;
                default:
                    break;
            }
        }
        return super.onKeyEvent(event);
    }
    public void onAccessibilityEvent(AccessibilityEvent event) {

    }
    public int onStartCommand(Intent intent, int flags, int startId) {
            final boolean choice[] = intent.getBooleanArrayExtra("data");
            MyThread = new Thread(new Runnable() {
                @Override
                public void run() {
                    Read reader = new Read();
                    Uiutil Finder = new Uiutil();
                    String[] appnames =AppInfo.appnames;
                    while (MyApplication.permission) {
                        Log.v("我在运行", "我是无障碍");
                        for (int i = 0; i < choice.length; i++) {
                            if (choice[i]) {
                                try {
                                    reader.getClass().getDeclaredMethod(appnames[i], Uiutil.class).invoke(reader, Finder);
                                } catch (IllegalAccessException e) {
                                    e.printStackTrace();
                                } catch (InvocationTargetException e) {
                                    e.printStackTrace();
                                } catch (NoSuchMethodException e) {
                                    e.printStackTrace();
                                }
                            } else {
                            }
                        }
                    }
                    Log.v("运行完毕","完毕");
                }
            });
            MyThread.start();
        return super.onStartCommand(intent, flags, startId);
    }

    public void onInterrupt() {

    }
    private boolean checkAccessibilityEnabled(String serviceName) {
        List<AccessibilityServiceInfo> accessibilityServices =
                mAccessibilityManager.getEnabledAccessibilityServiceList(AccessibilityServiceInfo.FEEDBACK_GENERIC);
        for (AccessibilityServiceInfo info : accessibilityServices) {
            if (info.getId().equals(serviceName)) {
                return true;
            }
        }
        return false;
    }


    class Uiutil {
        public void OpenAPP(String var1) {
            PackageManager var2 = getApplicationContext().getPackageManager();
            new Intent();
            Intent var3 = var2.getLaunchIntentForPackage(var1);
                getApplicationContext().startActivity(var3);
        }
        public List<AccessibilityNodeInfo> findNodesByText(String text) throws InterruptedException {
            List<AccessibilityNodeInfo> result = new ArrayList<>();
//                List<AccessibilityWindowInfo> windowInfos =getWindows();
            int time=search_count;
            Log.v("按照文字查找",text);
            while (result.size() == 0&&time>0){
                AccessibilityNodeInfo nodeInfo = getRootInActiveWindow();
                if (nodeInfo != null) {
                    Log.v("有控件，找",text);
                    result=nodeInfo.findAccessibilityNodeInfosByText(text);
                }
                Thread.sleep(1000);
                time-=1;
            }
            return result;
        }
        public List<AccessibilityNodeInfo> findNodesById(String viewId) throws InterruptedException {
            List<AccessibilityNodeInfo> result = new ArrayList<>();
            int time=search_count;
            Log.v("按照控件查找",viewId);
            while (result.size() == 0&&time>0){
                AccessibilityNodeInfo nodeInfo = getRootInActiveWindow();
                if (nodeInfo != null) {
                    result=nodeInfo.findAccessibilityNodeInfosByViewId(viewId);
                }
                Thread.sleep(1000);
                time-=1;
            }
            return result;
        }

        /**
         * 模拟点击事件
         *
         * @param nodeInfo nodeInfo
         */
        public void performViewClick(AccessibilityNodeInfo nodeInfo) {
            if (nodeInfo == null) {
                return;
            }
            while (nodeInfo != null) {
                if (nodeInfo.isClickable()) {
                    nodeInfo.performAction(AccessibilityNodeInfo.ACTION_CLICK);
                    break;
                }
                nodeInfo = nodeInfo.getParent();
            }
        }

        /**
         * 模拟返回操作
         */
        public void performBackClick() {
            try {
                Thread.sleep(500);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            Log.v("全局操作","返回");
            performGlobalAction(GLOBAL_ACTION_BACK);
        }

        /**
         * 模拟下滑操作
         */
        public void performScrollBackward() {
            try {
                Thread.sleep(100);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            Log.v("全局操作","下滑");
            performGlobalAction(AccessibilityNodeInfo.ACTION_SCROLL_BACKWARD);
        }

        /**
         * 模拟上滑操作
         */
        public void performScrollForward() {
            try {
                Thread.sleep(100);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            Log.v("全局操作","上滑");
            performGlobalAction(AccessibilityNodeInfo.ACTION_SCROLL_FORWARD);
        }

        /**
         * 查找对应文本的View
         *
         * @param text text
         * @return View
         */
        public AccessibilityNodeInfo findViewByText(String text) {
            return findViewByText(text, false);
        }

        /**
         * 查找对应文本的View
         *
         * @param text      text
         * @param clickable 该View是否可以点击
         * @return View
         */
        public AccessibilityNodeInfo findViewByText(String text, boolean clickable) {
            AccessibilityNodeInfo accessibilityNodeInfo = getRootInActiveWindow();
            if (accessibilityNodeInfo == null) {
                return null;
            }
            List<AccessibilityNodeInfo> nodeInfoList = accessibilityNodeInfo.findAccessibilityNodeInfosByText(text);
            if (nodeInfoList != null && !nodeInfoList.isEmpty()) {
                for (AccessibilityNodeInfo nodeInfo : nodeInfoList) {
                    if (nodeInfo != null && (nodeInfo.isClickable() == clickable)) {
                        return nodeInfo;
                    }
                }
            }
            return null;
        }

        /**
         * 查找对应ID的View
         *
         * @param id id
         * @return View
         */
        @TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR2)
        public AccessibilityNodeInfo findViewByID(String id) {
            AccessibilityNodeInfo accessibilityNodeInfo = getRootInActiveWindow();
            if (accessibilityNodeInfo == null) {
                return null;
            }
            List<AccessibilityNodeInfo> nodeInfoList = accessibilityNodeInfo.findAccessibilityNodeInfosByViewId(id);
            if (nodeInfoList != null && !nodeInfoList.isEmpty()) {
                for (AccessibilityNodeInfo nodeInfo : nodeInfoList) {
                    if (nodeInfo != null) {
                        return nodeInfo;
                    }
                }
            }
            return null;
        }

        public void clickTextViewByText(String text) {
            Log.v("按照文字查找",text);
            AccessibilityNodeInfo accessibilityNodeInfo = getRootInActiveWindow();
            if (accessibilityNodeInfo == null) {
                return;
            }
            List<AccessibilityNodeInfo> nodeInfoList = accessibilityNodeInfo.findAccessibilityNodeInfosByText(text);
            if (nodeInfoList != null && !nodeInfoList.isEmpty()) {
                for (AccessibilityNodeInfo nodeInfo : nodeInfoList) {
                    if (nodeInfo != null) {
                        performViewClick(nodeInfo);
                        break;
                    }
                }
            }
        }

        @TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR2)
        public void clickTextViewByID(String id) {
            Log.v("按照ID查找",id);
            AccessibilityNodeInfo accessibilityNodeInfo = getRootInActiveWindow();
            if (accessibilityNodeInfo == null) {
                return;
            }
            List<AccessibilityNodeInfo> nodeInfoList = accessibilityNodeInfo.findAccessibilityNodeInfosByViewId(id);
            if (nodeInfoList != null && !nodeInfoList.isEmpty()) {
                for (AccessibilityNodeInfo nodeInfo : nodeInfoList) {
                    if (nodeInfo != null) {
                        performViewClick(nodeInfo);
                        break;
                    }
                }
            }
        }

        /**
         * 模拟输入
         *
         * @param nodeInfo nodeInfo
         * @param text     text
         */
        public void inputText(AccessibilityNodeInfo nodeInfo, String text) {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
                Bundle arguments = new Bundle();
                arguments.putCharSequence(AccessibilityNodeInfo.ACTION_ARGUMENT_SET_TEXT_CHARSEQUENCE, text);
                nodeInfo.performAction(AccessibilityNodeInfo.ACTION_SET_TEXT, arguments);
            } else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR2) {
                ClipboardManager clipboard = (ClipboardManager) getSystemService(Context.CLIPBOARD_SERVICE);
                ClipData clip = ClipData.newPlainText("label", text);
                clipboard.setPrimaryClip(clip);
                nodeInfo.performAction(AccessibilityNodeInfo.ACTION_FOCUS);
                nodeInfo.performAction(AccessibilityNodeInfo.ACTION_PASTE);
            }
        }
    }
    public void showtoast(final String text){
        Handler handlerThree=new Handler(Looper.getMainLooper());
        handlerThree.post(new Runnable(){
            public void run(){
                Toast.makeText(MyApplication.getContext(),text, Toast.LENGTH_SHORT).show();
            }
        });//
    }
}

